package com.hupu.jrs.ui.gallery

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.provider.MediaStore
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.ImageView
import android.widget.ListPopupWindow
import android.widget.TextView
import android.widget.Toast
import java.io.File
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import java.util.Locale
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.hupu.jrs.R
import com.hupu.jrs.bean.Folder
import com.hupu.jrs.bean.Image
import com.hupu.jrs.ui.BaseSwipeBackActivity

/**
 * Created by sll on 2016/3/9.
 * TODO 待重构
 */
class GalleryActivity : BaseSwipeBackActivity(), GalleryContract.View, ImageAdapter.OnImageItemClickListener, AdapterView.OnItemClickListener {



    @BindView(R.id.toolbar)
    internal var toolbar: Toolbar? = null
    @BindView(R.id.recyclerView)
    internal var recyclerView: RecyclerView? = null
    @BindView(R.id.tvFolder)
    internal var tvFolder: TextView? = null
    @BindView(R.id.btCommit)
    internal var btCommit: Button? = null

    @Inject
    internal var mPresenter: GalleryPresenter? = null
    @Inject
    internal var mImageAdapter: ImageAdapter? = null
    @Inject
    internal var mFolderAdapter: FolderAdapter? = null

    // 结果数据
    private var resultList: ArrayList<String>? = ArrayList()
    private var mFolderPopupWindow: ListPopupWindow? = null

    protected override val isApplyStatusBarTranslucency: Boolean
        get() = true

    protected override val isApplyStatusBarColor: Boolean
        get() = true

    private var mTmpFilePath: String? = null

    override fun initContentView(): Int {
        return R.layout.activity_gallery
    }

    override fun initInjector() {
        DaggerGalleryComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule())
                .build()
                .inject(this)
    }

    override fun initUiAndListener() {
        ButterKnife.bind(this)
        mPresenter!!.attachView(this)
        setTitle("图库")
        initToolBar(toolbar)
        val selectImages = getIntent().getStringArrayListExtra("selectImages")
        if (selectImages != null && selectImages!!.size > 0) {
            resultList = selectImages
            btCommit!!.text = String.format("完成( %d/%d )", resultList!!.size, MAX)
        }
        val layoutManager = GridLayoutManager(getApplicationContext(), 4)
        recyclerView!!.layoutManager = layoutManager
        recyclerView!!.adapter = mImageAdapter
        recyclerView!!.itemAnimator = DefaultItemAnimator()
        mImageAdapter!!.setOnImageItemClickListener(this)
        createPopupFolderList()
    }

    private fun createPopupFolderList() {
        mFolderPopupWindow = ListPopupWindow(this)
        mFolderPopupWindow!!.setAdapter(mFolderAdapter)
        mFolderPopupWindow!!.setContentWidth(ListPopupWindow.MATCH_PARENT)
        mFolderPopupWindow!!.width = ListPopupWindow.MATCH_PARENT
        mFolderPopupWindow!!.height = ListPopupWindow.MATCH_PARENT
        mFolderPopupWindow!!.anchorView = toolbar
        mFolderPopupWindow!!.isModal = true
        mFolderPopupWindow!!.animationStyle = R.style.popwindow_anim_style
        mFolderPopupWindow!!.setOnItemClickListener(this)
    }

    protected fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        mPresenter!!.onImageAndFolderReceive()
    }

    override fun renderFolders(folders: MutableList<Folder>) {
        mFolderAdapter!!.bind(folders)
    }

    override fun renderImages(images: MutableList<Image>) {
        mImageAdapter!!.bind(images)
        if (resultList != null && resultList!!.size > 0) {
            mImageAdapter!!.setDefaultSelected(resultList!!)
        }
    }

    override fun click(image: Image?, view: ImageView) {
        if (image != null) {
            if (resultList!!.contains(image!!.path)) {
                resultList!!.remove(image!!.path)
                if (resultList!!.size != 0) {
                    btCommit!!.text = String.format("完成( %d/%d )", resultList!!.size, MAX)
                } else {
                    btCommit!!.text = "完成"
                }
            } else {
                // 判断选择数量问题
                if (MAX == resultList!!.size) {
                    Toast.makeText(this, String.format("最多选择 %d 张图片哦", MAX), Toast.LENGTH_SHORT).show()
                    return
                }
                resultList!!.add(image!!.path)
                btCommit!!.text = String.format("完成( %d/%d )", resultList!!.size, MAX)
            }
            mImageAdapter!!.select(image, view)
        }
    }

    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        mFolderAdapter!!.selectIndex = position
        Handler().postDelayed({
            mFolderPopupWindow!!.dismiss()
            if (position == 0) {
                mPresenter!!.onImageAndFolderReceive()
                tvFolder!!.text = "最近照片"
            } else {
                val folder = parent.adapter.getItem(position) as Folder
                if (null != folder) {
                    mImageAdapter!!.bind(folder!!.images)
                    tvFolder!!.setText(folder!!.name)
                    // 设定默认选择
                    if (resultList != null && resultList!!.size > 0) {
                        mImageAdapter!!.setDefaultSelected(resultList!!)
                    }
                }
            }
            // 滑动到最初始位置
            recyclerView!!.smoothScrollToPosition(0)
        }, 100)
    }

    @OnClick(R.id.tvFolder)
    internal fun setTvFolderClick() {
        if (mFolderPopupWindow!!.isShowing) {
            mFolderPopupWindow!!.dismiss()
        } else {
            mFolderPopupWindow!!.show()
            var index = mFolderAdapter!!.selectIndex
            index = if (index == 0) index else index - 1
            mFolderPopupWindow!!.listView!!.setSelection(index)
        }
    }

    @OnClick(R.id.btCommit)
    internal fun setBtCommitClick() {
        if (resultList != null && resultList!!.size > 0) {
            // 返回已选择的图片数据
            val data = Intent()
            data.putStringArrayListExtra(EXTRA_RESULT, resultList)
            setResult(RESULT_OK, data)
            finish()
        }
    }

    @OnClick(R.id.rlCamera)
    internal fun setRlCameraClick() {
        // 跳转到系统照相机
        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (cameraIntent.resolveActivity(getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            mTmpFilePath = createTmpFile()
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(File(mTmpFilePath!!)))
            startActivityForResult(cameraIntent, REQUEST_CAMERA)
        } else {
            Toast.makeText(this, "没有系统相机", Toast.LENGTH_SHORT).show()
        }
    }

    fun createTmpFile(): String {
        val state = Environment.getExternalStorageState()
        if (state == Environment.MEDIA_MOUNTED) {
            // 已挂载
            val pic = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            if (!pic.exists()) {
                pic.mkdirs()
            }
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
            val fileName = "tui_" + timeStamp + ""
            return pic.absolutePath + File.separator + fileName + ".jpg"
        } else {
            val cacheDir = getCacheDir()
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(Date())
            val fileName = "tui_" + timeStamp + ""
            return cacheDir.toString() + File.separator + fileName + ".jpg"
        }
    }

    protected override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        mTmpFilePath = savedInstanceState.getString("mTmpFilePath")
        resultList = savedInstanceState.getStringArrayList("resultList")
    }

    protected override fun onSaveInstanceState(outState: Bundle) {
        outState.putString("mTmpFilePath", mTmpFilePath)
        outState.putStringArrayList("resultList", resultList)
        super.onSaveInstanceState(outState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        // 相机拍照完成后，返回图片路径
        if (requestCode == REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                if (!TextUtils.isEmpty(mTmpFilePath)) {
                    resultList!!.add(this!!.mTmpFilePath!!)
                    val intent = Intent()
                    intent.putStringArrayListExtra(EXTRA_RESULT, resultList)
                    setResult(RESULT_OK, intent)
                    finish()
                }
            } else {
                val mTmpFile = File(mTmpFilePath!!)
                if (mTmpFile.exists()) {
                    mTmpFile.delete()
                }
            }
        }
    }

    protected override fun onDestroy() {
        super.onDestroy()
        mPresenter!!.detachView()
    }

    companion object {

        fun startActivity(mActivity: Activity, selectImages: ArrayList<String>) {
            val intent = Intent(mActivity, GalleryActivity::class.java)
            intent.putExtra("selectImages", selectImages)
            mActivity.startActivityForResult(intent, REQUEST_IMAGE)
        }

        val REQUEST_IMAGE = 101
        val EXTRA_RESULT = "select_result"

        private val MAX = 5
        // 请求加载系统照相机
        private val REQUEST_CAMERA = 100
    }
}
